import requests
import json
from bs4 import BeautifulSoup
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import RGBColor, Pt

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
}

with open('xing.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    chapterViewList = data["result"]["chapterList"][0]["chapterViewList"]
    num = 0
    for i in chapterViewList:
        num = num + 1
        if num < 2:
            url = 'https://read.zongheng.com/chapter/1330759/' + str(i["chapterId"]) + '.html'
            response = requests.get(url=url, headers=headers)
            soup = BeautifulSoup(response.content.decode("utf-8"), 'html.parser')
            
            # 创建Word文档
            doc = Document()
            
            # 添加章节标题
            chapter_title = soup.find('div', {'class': 'title_txtbox'}).string
            title = doc.add_paragraph(chapter_title, style='Heading 1')
            title.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
            run = title.runs[0]
            run.font.color.rgb = RGBColor(0, 0, 255)  # 蓝色
            run.font.size = Pt(18)
            
            # 添加章节内容
            paragraphs = soup.findAll('p')
            for p in paragraphs:
                para = doc.add_paragraph(p.text)
                run = para.runs[0]
                run.font.color.rgb = RGBColor(0, 0, 255)  # 蓝色
                run.font.size = Pt(18)
            
            # 保存文档
            doc.save(f'{chapter_title}.docx')